package edu.indiana.cs.b534.torrent.impl;

import java.util.Collection;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Vector;

public class PieceData {
	 	private List<PieceInfo> piecesToBeDownloaded = new Vector<PieceInfo>();
	    private List<PieceInfo> piecesBeingDownloaded = new Vector<PieceInfo>();
	    private Map<Integer, PieceInfo> piecesFinishedDownloading = new Hashtable<Integer, PieceInfo>();
	    
	    
	    public synchronized void initPiece(PieceInfo piece){
	    	if(piece == null){
	    		throw new RuntimeException("Piece Can not be null");
	    	}
	    	piecesToBeDownloaded.add(piece);
	    }
	    
	    public synchronized void pieceStartDownloading(PieceInfo piece){
	    	if(piece == null){
	    		throw new RuntimeException("Piece Can not be null");
	    	}
	    	piecesBeingDownloaded.add(piece);
	    	piecesToBeDownloaded.remove(piece);
	    }
	    
	    public synchronized void pieceDownloaded(PieceInfo piece){
	    	if(piece == null){
	    		throw new RuntimeException("Piece Can not be null");
	    	}
	    	piecesFinishedDownloading.put(piece.getIndex(), piece);
	    	piecesBeingDownloaded.remove(piece);
	    }
	    
	    public synchronized void pieceCancelled(PieceInfo piece){
	    	if(piece == null){
	    		throw new RuntimeException("Piece Can not be null");
	    	}
	    	piecesToBeDownloaded.add(piece);
	    	piecesBeingDownloaded.remove(piece);
	    }
	    
	    public synchronized int findPieceINeedAndHeHas(PeerInstance peer){
	    	Collection<Integer> peicesPeerHas = peer.getPeerDescription().getPiecesList();
	    	for(PieceInfo piece:piecesToBeDownloaded){
	    		if(peicesPeerHas.contains(piece.getIndex())){
	    			return piece.getIndex();
	    		}
	    	}
	    	return -1;
	    }
	    
	    public synchronized boolean hasCompleted(){
	    	if(piecesToBeDownloaded.size() > 0 || piecesBeingDownloaded.size() > 0){
	    		return false;
	    	}else{
	    		return true;
	    	}
	    }
	    
	    public synchronized String status(){
	    	return "pieces "+ piecesFinishedDownloading.size() + " finshed "+ piecesBeingDownloaded.size() + " downloading "+ piecesToBeDownloaded.size() + " todownloded";
	    }

}
